package org.bunny.vehicle.service.admin;

import java.util.Date;

import org.bunny.vehicle.entity.Expense;
import org.bunny.vehicle.entity.Vehicle;
import org.bunny.vehicle.service.BaseService;
import org.bunny.vehicle.util.Const;
import org.bunny.vehicle.util.JSON;
import org.bunny.vehicle.util.Utils;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.spring.SpringCreator;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@RemoteProxy(creator = SpringCreator.class)
@Service
public class AdminExpenseService extends BaseService {

	public Page<Expense> getList(String json) {
		JSONObject obj = JSON.parseObject(json);

		byte verifyStatus = JSON.getByte(obj, "verifyStatus");
		int page = JSON.getInteger(obj, "page");

		return expenseRepository.findByVerifyStatus(verifyStatus, new PageRequest(page,
				Const.PAGE_SIZE, Sort.Direction.DESC, "id"));
	}

	public boolean del(String json) {
		try {
			JSONArray array = JSONArray.parseArray(json);

			for (Object obj : array) {
				int id = Utils.parseInt(obj);
				if (1 > id) {
					return false;
				}
				Expense expense = expenseRepository.findOne(id);
				if (null != expense) {
					vehicleRepository.delete(id);
				}
			}
		} catch (Exception e) {
			log.error(e + json, e);
			return false;
		}
		return true;
	}

	public boolean save(String json) {
		JSONObject obj = JSON.parseObject(json);

		byte classification = JSON.getByte(obj, "classification");
		byte verifyStatus = JSON.getByte(obj, "verifyStatus");
		int id = JSON.getInteger(obj, "id");
		String vehicleLicensePlate = JSON.getString(obj, "vehicleLicensePlate");
		String remark = JSON.getString(obj, "remark");
		String priceString = JSON.getString(obj, "price");

		if (Utils.isEmpty(vehicleLicensePlate)) {
			return false;
		}

		Expense expense;
		if (id > 0) {
			expense = expenseRepository.findOne(id);
			if (null == expense) {
				return false;
			}
		} else {
			expense = new Expense();
			expense.setCommitUser(getUser());
			expense.setCommitDate(new Date());
		}

		Vehicle vehicle = vehicleRepository.findByLicensePlate(vehicleLicensePlate);
		if (null == vehicle) {
			return false;
		}

		expense.setClassification(classification);
		expense.setCommitDate(new Date());
		expense.setRemark(remark);
		expense.setPrice(Utils.stringToMoney(priceString));
		expense.setVehicle(vehicle);
		expense.setVerifyUser(getUser());
		expense.setVerifyDate(new Date());
		expense.setVerifyStatus(verifyStatus);

		return null != expenseRepository.save(expense);
	}
}
